package com.excesys.exsecs.scada.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.annotation.ResponseExcel;
import com.excesys.exsecs.common.file.core.FileProperties;
import com.excesys.exsecs.common.log.annotation.SysLog;
import com.excesys.exsecs.scada.entity.ScadaDevice;
import com.excesys.exsecs.scada.entity.ScadaEntity;
import com.excesys.exsecs.scada.entity.ScadaProperty;
import com.excesys.exsecs.scada.properties.PathProperties;
import com.excesys.exsecs.scada.service.ScadaPropertyService;
import com.excesys.exsecs.scada.util.JsonProcess;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 组态配置表
 *
 * @author tzh
 * @date 2024-05-10 16:01:26
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/scadaProperty" )
@Tag(description = "scadaProperty" , name = "组态配置表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ScadaPropertyController {

    private final  ScadaPropertyService scadaPropertyService;
	private final FileProperties properties;
	private final JsonProcess jsonProcess;
	private final ScadaEntity scadaEntity;

	@Operation(summary = "一键同步所有JSON文件" , description = "同步所有JSON文件" )
	@PostMapping("/changeAllJson")
	public R changeAllJson(){
		Date start = new Date();
		jsonProcess.ChangeAllJson();
		Date end = new Date();
		long millisecond = end.getTime() - start.getTime();
		return R.ok("","更新成功，用时："+millisecond/1000+"秒");

	}

    /**
     * 分页查询
     * @param scadaProperty 组态配置表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_view')" )
    public R getScadaPropertyPage(@ParameterObject Page page, @ParameterObject ScadaProperty scadaProperty,Integer bindFlag) {
		IPage iPage = scadaPropertyService.selectAll(page, scadaProperty, bindFlag);
		return R.ok(iPage,"组态分页查询");
	}

    /**
     * 通过id查询组态配置表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_view')" )
    public R<ScadaProperty> getById(@PathVariable("id" ) Long id) {
        return R.ok(scadaPropertyService.getById(id));
    }

    /**
     * 新增组态
     * @param scadaProperty 组态配置表
     * @return R
     */
    @Operation(summary = "新增组态配置表" , description = "新增组态配置表" )
    @SysLog("新增组态配置表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_add')" )
    public R save(@RequestBody ScadaProperty scadaProperty) {
        return R.ok(scadaPropertyService.save(scadaProperty));
    }

    /**
     * 修改组态配置表
     * @param scadaProperty 组态配置表
     * @return R
     */
    @Operation(summary = "修改组态配置表" , description = "修改组态配置表" )
    @SysLog("修改组态配置表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_edit')" )
    public R updateById(@RequestBody ScadaProperty scadaProperty) {
		Date start = new Date();
		boolean update = scadaPropertyService.updateById(scadaProperty);

		String[] split = scadaProperty.getFileName().split("\\.");
		String outPutDir = scadaEntity.getBasePath()+ FileUtil.FILE_SEPARATOR
				+ "package" + FileUtil.FILE_SEPARATOR+ split[0];
		//判断是否是l5l vue2或vue3组件包
		File[] ls = FileUtil.ls(outPutDir);
		List<String> vueDir = new ArrayList<String>(Arrays.asList("meta2d-vue2","meta2d-vue3"));
		if(ls.length > 0 && ls[0].getName().contains("meta2d-vue")){
			String dirname = ls[0].getName();
			int i = dirname.lastIndexOf("meta2d-vue");
			String subdirname = dirname.substring(i);
			//替换image
			String filePath = outPutDir + FileUtil.FILE_SEPARATOR + subdirname + FileUtil.FILE_SEPARATOR + "public";
			jsonProcess.ChangeJson(filePath,split[0]);
		}
		Date end = new Date();
		long millisecond = end.getTime() - start.getTime();
		return R.ok(update,"更新成功，用时："+millisecond/1000+"秒");
    }

    /**
     * 通过id删除组态配置表
     * @param
     * @return R
     */
    @Operation(summary = "通过id删除组态配置表" , description = "通过id删除组态配置表" )
    @SysLog("通过id删除组态配置表" )
    @DeleteMapping("/removeDeep")
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_del')" )
    public R removeDeep(@RequestBody Long[] ids) {

		Boolean aBoolean = scadaPropertyService.removeDeep(ids);
		if(aBoolean){
			return R.ok(true,"删除成功");
		}
		return R.failed("组态已绑定设备，请先解除设备的绑定");
    }

    /**
     * 通过id删除组态配置表子表数据
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除组态配置表子表数据" , description = "通过id删除组态配置表子表数据" )
    @SysLog("通过id删除组态配置表子表数据" )
    @DeleteMapping()
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(scadaPropertyService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 导出excel 表格
     * @param scadaProperty 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('scada_scadaProperty_export')" )
    public List<ScadaProperty> export(ScadaProperty scadaProperty,Long[] ids) {
        return scadaPropertyService.list(Wrappers.lambdaQuery(scadaProperty).in(ArrayUtil.isNotEmpty(ids), ScadaProperty::getId, ids));
    }

	public R bindDevice(@RequestBody ScadaProperty scadaProperty, @RequestBody ScadaDevice scadaDevice){
		return null;
	}

}